#include "mainwidget.h"
#include "languagerecognizer.h"
#include "texttranslator.h"

#include <QBoxLayout>
#include <QPushButton>
#include <QTextBrowser>
#include <QTextEdit>

MainWidget::MainWidget(QWidget* parent)
    : QWidget(parent)
    , m_inputEdit(new QTextEdit(this))
    , m_outputTextBrowser(new QTextBrowser(this))
{
    QSize size(300, 100);
    m_inputEdit->setMinimumSize(size);
    m_inputEdit->setPlaceholderText(tr("Input text to translate..."));
    m_outputTextBrowser->setMinimumSize(size);

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_inputEdit);
    mainLayout->addSpacing(10);
    mainLayout->addWidget(m_outputTextBrowser);

    connect(m_inputEdit, &QTextEdit::textChanged, this, [=]() {
        m_outputTextBrowser->clear();
        LanguageRecognizer* recognizer = new LanguageRecognizer(this);
        connect(recognizer, &LanguageRecognizer::languageRecgnized, this, [=](const QString& text, Language language) {
            if (language == Language::Unknow)
                return;

            Language from = language;
            Language to = from == Language::En ? Language::Zh : Language::En;
            TextTranslator* textTranslator = new TextTranslator(this);
            connect(textTranslator, &TextTranslator::translateResult, this, [=](const QString& result) {
                if (text.trimmed() == m_inputEdit->toPlainText().trimmed())
                    m_outputTextBrowser->setText(result);

                textTranslator->deleteLater();
            });
            textTranslator->translate(text, from, to);
            recognizer->deleteLater();
        });

        recognizer->recognize(m_inputEdit->toPlainText());
    });
}
